package service;

import com.alibaba.fastjson.JSON;
import mapper.TeacherMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import pojos.common.ReplyMessage;
import pojos.subject.ClassInfo;
import pojos.subject.ClassInfoManager;
import pojos.subject.UserRelationshipManager;
import pojos.teacher.TeacherInfo;
import utils.Md5Utils;
import utils.SpecialCodeReplaceUtil;

import java.sql.Timestamp;
import java.util.List;

/**
 * 教师信息服务类
 */
public class TeacherInfoService {

    private Logger logger = LoggerFactory.getLogger(TeacherInfoService.class);
    private TeacherMapper teacherMapper;

    @Autowired
    public TeacherInfoService(TeacherMapper teacherMapper) {
        this.teacherMapper = teacherMapper;
    }

    /**
     * 查询所有教师基本信息
     */
    public List<TeacherInfo> queryAllTeachers(){
        try {
            return teacherMapper.queryAllTeachersBaseInfo();
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("查询教师基本信息异常！");

            return null;
        }
    }

    /**
     * 管理员添加教师信息
     */
    public ReplyMessage adminAddTeacher(TeacherInfo teacherInfo){
        ReplyMessage replyMessage = new ReplyMessage();
        try {
            // 查询登录名是否已经被占用
            String nameRe = SpecialCodeReplaceUtil.doReplace(teacherInfo.getName());
            Integer isExist = teacherMapper.isLoginNameExist(nameRe);
            if(isExist != null && isExist > 0){
                replyMessage.setStatus(400);
                replyMessage.setInfo("登录名已经被使用，请更换登录名称！");
                return replyMessage;
            }

            // 密码加密
            String passwordEn = Md5Utils.getMd5(teacherInfo.getPassword());
            teacherInfo.setPassword(passwordEn);
            teacherInfo.setName(nameRe);
            teacherInfo.setJoinTime(new Timestamp(System.currentTimeMillis()));
            teacherMapper.addTeacher(teacherInfo);
            replyMessage.setStatus(200);
            return replyMessage;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("添加教师信息失败，教师登录名称："+teacherInfo.getName()+"，登录密码："+teacherInfo.getPassword());

            replyMessage.setStatus(500);
            replyMessage.setInfo("服务器异常！");
            return replyMessage;
        }
    }

    /**
     * 查询所有教师名
     */
    public ReplyMessage queryAllTeacherName(){
        ReplyMessage replyMessage = new ReplyMessage();

        try {
            List<TeacherInfo> teacherInfoList = teacherMapper.queryAllTeacherName();
            if(teacherInfoList != null){
                replyMessage.setStatus(200);
                replyMessage.setInfo(JSON.toJSONString(teacherInfoList));
                return replyMessage;
            }
            replyMessage.setStatus(400);
            replyMessage.setInfo("查询结果为空！");
            return replyMessage;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("查询所有的教师登录名、姓名异常！");

            replyMessage.setStatus(500);
            replyMessage.setInfo("服务器异常，请稍后重试！");
            return replyMessage;
        }
    }

    /**
     * 教师登录检查
     */
    public ReplyMessage teacherLoginCheck(String userName, String password){
        ReplyMessage replyMessage = new ReplyMessage();

        try {
            String userNameRe = SpecialCodeReplaceUtil.doReplace(userName);
            TeacherInfo teacherInfo = teacherMapper.teacherLoginCheck(userNameRe);
            if(teacherInfo == null){
                replyMessage.setStatus(400);
                replyMessage.setInfo("用户不存在，请检查登录名！");
                return replyMessage;
            }

            if(teacherInfo.getAdminLock() != 0){
                replyMessage.setStatus(400);
                replyMessage.setInfo("账户被限制登录，请联系客服了解详情");
                return replyMessage;
            }

            if(teacherInfo.getSysLock() != 0){
                replyMessage.setStatus(400);
                replyMessage.setInfo("今天之内密码错误次数太多，为保护账号安全，账号已被锁定，请在24小时后重试或联系客服解决");
                return replyMessage;
            }

            String passwordEn = Md5Utils.getMd5(password);
            if(teacherInfo.getPassword().equals(passwordEn)){
                teacherInfo.setPassword("");
                teacherInfo.setName(userName);
                replyMessage.setStatus(200);
                replyMessage.setObject(teacherInfo);
                return replyMessage;
            }

            // 账号锁定
            int dayError = teacherInfo.getErrorTime();
            int teacherId = teacherInfo.getId();
            if(dayError > 10){
                teacherMapper.sysLockTeacher(teacherId);
                teacherMapper.sysAutoUnLock(teacherId);
            }
            teacherMapper.updateDayError(teacherId);

            replyMessage.setStatus(400);
            replyMessage.setInfo("密码错误！");
            return replyMessage;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("教师登录异常，登录名："+userName+"，登录密码："+password);

            replyMessage.setStatus(500);
            replyMessage.setInfo("服务器异常，请稍后重试！");
            return replyMessage;
        }
    }

    /**
     * 根据登录名称查找手机号
     */
    public TeacherInfo queryPhoneByName(String name, String phone){
        String nameRe = SpecialCodeReplaceUtil.doReplace(name);

        try {
            TeacherInfo teacherInfo = teacherMapper.queryPhoneByName(nameRe);
            if(teacherInfo != null){
                if(teacherInfo.getPhone().equals(phone)){
                    return teacherInfo;
                }
            }
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("根据教师登录名查找手机号异常，教师登录名："+name);

            return null;
        }
    }

    /**
     * 教师修改基础信息
     */
    public ReplyMessage teacherAlterBaseInfo(TeacherInfo teacherInfo){
        String realNameRe = SpecialCodeReplaceUtil.doReplace(teacherInfo.getRealName());
        String schoolRe = SpecialCodeReplaceUtil.doReplace(teacherInfo.getSchool());

        teacherInfo.setRealName(realNameRe);
        teacherInfo.setSchool(schoolRe);

        ReplyMessage replyMessage = new ReplyMessage();
        try {
            teacherMapper.teacherAlterBaseInfo(teacherInfo);
            replyMessage.setStatus(200);
            return replyMessage;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("教师修改基础信息异常，教师ID："+ teacherInfo.getId());

            replyMessage.setStatus(500);
            replyMessage.setInfo("服务器异常，请稍后重试！");
            return replyMessage;
        }
    }

    /**
     * 教师修改登录名
     */
    public ReplyMessage teacherAlterLoginName(TeacherInfo teacherInfo){
        String nameRe = SpecialCodeReplaceUtil.doReplace(teacherInfo.getName());
        teacherInfo.setName(nameRe);

        ReplyMessage replyMessage = new ReplyMessage();
        try {
            Integer isNameExist = teacherMapper.isLoginNameExist(nameRe);
            if(isNameExist != null && isNameExist > 0){
                replyMessage.setStatus(400);
                replyMessage.setInfo("该用户名已经被占用，请更换其他用户名");
                return replyMessage;
            }

            teacherMapper.alterLoginName(teacherInfo);
            replyMessage.setStatus(200);
            return replyMessage;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("教师修改登录名异常，教师ID："+teacherInfo.getId());

            replyMessage.setStatus(500);
            replyMessage.setInfo("服务器异常，请稍后重试！");
            return replyMessage;
        }
    }

    /**
     * 教师修改登录密码
     */
    public ReplyMessage teacherAlterPassword(String oldPassword,String newPassword,int id){
        ReplyMessage replyMessage = new ReplyMessage();
        try {
            // 查询原密码
            String queryPassword = teacherMapper.queryLoginPassword(id);
            String oldPasswordEn = Md5Utils.getMd5(oldPassword);
            if(queryPassword.equals(oldPasswordEn)){
                // 新密码加密
                String newPasswordEn = Md5Utils.getMd5(newPassword);
                teacherMapper.alterLoginPassword(id,newPasswordEn);
                replyMessage.setStatus(200);
                return replyMessage;
            }
            replyMessage.setStatus(400);
            replyMessage.setInfo("原密码不正确！");
            return replyMessage;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("教师修改密码异常，教师ID："+id);

            replyMessage.setStatus(500);
            replyMessage.setInfo("服务器异常，请稍后重试！");
            return replyMessage;
        }
    }

    /**
     * 教师修改手机号
     */
    public ReplyMessage teacherAlterPhone(TeacherInfo teacherInfo){
        ReplyMessage replyMessage = new ReplyMessage();

        try {
            teacherMapper.alterPhone(teacherInfo);
            replyMessage.setStatus(200);
            return replyMessage;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("教师修改手机号异常，教师ID："+teacherInfo.getId());

            replyMessage.setStatus(500);
            replyMessage.setInfo("服务器异常，请稍后重试！");
            return replyMessage;
        }
    }

    /**
     * 教师修改联系信息
     */
    public ReplyMessage alterConnectInfo(TeacherInfo teacherInfo){
        ReplyMessage replyMessage = new ReplyMessage();

        String weChatRe = SpecialCodeReplaceUtil.doReplace(teacherInfo.getWeChat());
        teacherInfo.setWeChat(weChatRe);

        try {
            teacherMapper.alterConnectInfo(teacherInfo);
            replyMessage.setStatus(200);
            return replyMessage;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("教师修改联系信息异常，教师ID："+teacherInfo.getId());

            replyMessage.setStatus(500);
            replyMessage.setInfo("服务器异常，请稍后重试！");
            return replyMessage;
        }
    }

    /**
     * 教师查询自己的用户关系
     */
    public ReplyMessage queryAllSelfRelationship(int teacherId){
        ReplyMessage replyMessage = new ReplyMessage();
        try {
            List<UserRelationshipManager> subjectManagerList = teacherMapper.teacherQueryRelation(teacherId,1);
            if(subjectManagerList != null){
                replyMessage.setStatus(200);
                replyMessage.setInfo(JSON.toJSONString(subjectManagerList));
                return replyMessage;
            }

            replyMessage.setStatus(400);
            replyMessage.setInfo("查询结果为空！");
            return replyMessage;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("教师查询自己的关系异常，教师ID："+teacherId);

            replyMessage.setStatus(500);
            replyMessage.setInfo("服务器异常，请稍后重试！");
            return replyMessage;
        }
    }

    /**
     * 教师添加课程信息
     */
    public ReplyMessage teacherAddClassInfo(ClassInfo classInfo){
        String classNameRe = SpecialCodeReplaceUtil.doReplace(classInfo.getClassName());
        String commentRe = SpecialCodeReplaceUtil.doReplace(classInfo.getComment());
        classInfo.setClassName(classNameRe);
        classInfo.setComment(commentRe);

        ReplyMessage replyMessage = new ReplyMessage();
        try {
            teacherMapper.teacherAddClass(classInfo);
            replyMessage.setStatus(200);
            return replyMessage;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("教师添加课程信息异常，关系ID："+classInfo.getRelationId());

            replyMessage.setStatus(500);
            replyMessage.setInfo("服务器异常，请稍后重试！");
            return replyMessage;
        }
    }

    /**
     * 教师查找课程信息
     */
    public ClassInfoManager queryClassInfo(int classId){
        try {
            return teacherMapper.queryClassInfo(classId,1);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("教师查找课程信息异常，课程ID："+classId);

            return null;
        }
    }

    /**
     * 教师修改课程信息
     */
    public ReplyMessage alterClassInfo(ClassInfo classInfo){
        String classNameRe = SpecialCodeReplaceUtil.doReplace(classInfo.getClassName());
        String classCommentRe = SpecialCodeReplaceUtil.doReplace(classInfo.getComment());

        classInfo.setClassName(classNameRe);
        classInfo.setComment(classCommentRe);

        ReplyMessage replyMessage = new ReplyMessage();
        try {
            teacherMapper.alterClassInfo(classInfo);
            replyMessage.setStatus(200);
            return replyMessage;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("教师修改课程信息异常，课程ID："+classInfo.getClassId());

            replyMessage.setStatus(500);
            replyMessage.setInfo("服务器异常，请稍后重试！");
            return replyMessage;
        }
    }

    /**
     * 教师删除课程信息
     */
    public ReplyMessage deleteClassInfo(int classId){
        ReplyMessage replyMessage = new ReplyMessage();

        try {
            teacherMapper.deleteClassInfo(classId);
            replyMessage.setStatus(200);
            return replyMessage;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("教师删除课程信息异常，课程ID："+classId);

            replyMessage.setStatus(500);
            replyMessage.setInfo("服务器异常，请稍后重试！");
            return replyMessage;
        }
    }

    /**
     * 查询教师当天课程信息
     */
    public ReplyMessage queryTeacherCurrentClassInfo(int teacherId){
        ReplyMessage replyMessage = new ReplyMessage();
        try {
            List<ClassInfoManager> classInfoManagerList = teacherMapper.queryTeacherCurrentClassInfo(teacherId);
            if(classInfoManagerList != null){
                replyMessage.setStatus(200);
                replyMessage.setInfo(JSON.toJSONString(classInfoManagerList));
                return replyMessage;
            }
            replyMessage.setStatus(400);
            replyMessage.setInfo("查询结果为空！");
            return replyMessage;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("教师查询当天课程信息异常，教师ID："+teacherId);

            replyMessage.setStatus(500);
            replyMessage.setInfo("服务器异常，请稍后重试！");
            return replyMessage;
        }
    }
}
